import Vue from 'vue'
import Router from 'vue-router'

import Login from "../components/Login";
import Home from "../components/Home";

import Welcome from "../components/Welcome";
import Users from "../components/user/Users";
import Rights from "../components/power/Rights";
import Roles from "../components/power/Roles";
import Categories from "../components/goods/Categories";
import Params from "../components/goods/Params";
import Goods from "../components/goods/Goods";
import Order from "../components/order/Order";
import Report from "../components/report/Report";

import Add from "../components/goods/Add";

Vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router=new Router({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: "/home",
      component:Home,
      children:[
        {path: "welcome", component:Welcome},
        {path: "users", component:Users},
        {path: "rights", component:Rights},
        {path: "roles", component:Roles},
        {path: "categories", component:Categories},
        {path: "params", component:Params},
        {path: "goods", component:Goods},
        {path: "goods/add", component:Add},
        {path: "orders", component:Order},
        {path: "reports", component:Report},
        {path: "/home", redirect:'/home/welcome'},
      ]
    },
    {
      path: "/",
      redirect:"/login"
    }
  ]
})

//挂载路由导航守卫
router.beforeEach((to,from,next)=>{
  //to将要访问的路径，from从那个路径跳转而来。
  //next是一个函数，允许放行。next()放行next("/login")强制跳转。
  if(to.path==="/login") return next();
  else if(to.path.includes("/goods/")&&to.path!=="/home/goods/add") {
    return next("/home/" + to.path.substr(to.path.lastIndexOf("/") + 1));
  }
  const tokenStr=window.sessionStorage.getItem("token");
  if(!tokenStr) return next("/login");
  next();
})

export default router;
